package com.kjlink.internal.workreport.report.controller;

import cn.xuqiudong.common.base.model.BaseResponse;
import cn.xuqiudong.common.base.model.PageInfo;
import cn.xuqiudong.common.base.model.Remind;
import cn.xuqiudong.common.util.JsonUtil;
import com.kjlink.internal.workreport.base.controller.BaseController;
import com.kjlink.internal.workreport.base.enums.InputtableDateEnum;
import com.kjlink.internal.workreport.helper.SessionHelper;
import com.kjlink.internal.workreport.jira.service.JiraService;
import com.kjlink.internal.workreport.project.service.ProjectService;
import com.kjlink.internal.workreport.report.lookup.WorkReportLookup;
import com.kjlink.internal.workreport.report.model.WorkReport;
import com.kjlink.internal.workreport.report.service.WorkReportService;
import com.kjlink.internal.workreport.report.vo.DayReportVo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;

/**
 * 功能: : 控制层
 *
 * @author Vic.xu
 * @since 2024-04-29 13:37
 */
@RestController
@RequestMapping("/report")
public class WorkReportController extends BaseController<WorkReportService, WorkReport> {


    @Resource
    private ProjectService projectService;

    @Resource
    private JiraService jiraService;

    /**
     * 列表页
     */
    @RequestMapping(value = "/", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView index(WorkReportLookup lookup) {
        ModelAndView modelAndView = new ModelAndView("report/list");
        /**
         * 设置权限
         */
        lookup.initAuthority();

        PageInfo<WorkReport> pager = service.page(lookup);
        pager.setLookup(lookup);
        modelAndView.addObject("pager", pager);
        return modelAndView;
    }

    /**
     * 研发经理可查看的日报列表：只能查看自己创建的项目相关的日报
     */
    @RequestMapping(value = "/devManagerList", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView devManagerList(WorkReportLookup lookup) {
        ModelAndView modelAndView = new ModelAndView("report/project-report-list");
        /**
         * 设置权限
         */
        lookup.markDevManager();

        PageInfo<WorkReport> pager = service.page(lookup);
        modelAndView.addObject("pager", pager);
        return modelAndView;
    }


    /**
     * 某日的详情
     *
     * @param id day对应的id
     */
    @GetMapping("/day/{id}")
    public ModelAndView dayDetail(@PathVariable Integer id) {
        ModelAndView modelAndView = new ModelAndView("report/day");
        DayReportVo dayReport = service.getDayReport(id);
        modelAndView.addObject("day", dayReport);
        return modelAndView;
    }

    /**
     * 某日的详情
     *
     * @param date   日期
     * @param userId 用户id
     * @see #dayDetail(Integer)
     */
    @GetMapping("/day/detail")
    public ModelAndView dayDetail(@DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date, Integer userId) {
        ModelAndView modelAndView = new ModelAndView("report/day");
        DayReportVo dayReport = service.getDayReportByDate(userId, date);
        modelAndView.addObject("day", dayReport);
        return modelAndView;
    }


    /**
     * 删除
     */
    @GetMapping("/delete/{id}")
    public ModelAndView delete(@PathVariable Integer id, RedirectAttributes attrs) {
        service.delete(id);
        return redirectHome(attrs);
    }

    /**
     * 删除
     */
    @Deprecated
    @PostMapping("/delete/{id}")
    public ModelAndView delete(@PathVariable Integer id,
                               @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date,
                               RedirectAttributes attrs) {
        ModelAndView mv = new ModelAndView("redirect:/report/add/" + InputtableDateEnum.getByDate(date));
        service.delete(id);
        attrs.addFlashAttribute(Remind.success().setMessage("保存成功"));
        return mv;
    }


    /**
     * 前往新增页面
     *
     * @return
     */
    @GetMapping("/form")
    public ModelAndView form() {
        ModelAndView mv = new ModelAndView("report/form");
        mv.addObject("dates", InputtableDateEnum.values());

        return mv;
    }

    @PostMapping("/save")
    public ModelAndView save(WorkReport workReport, RedirectAttributes attrs) {
        workReport.setUserId(SessionHelper.currentUserId());
        ModelAndView mv = new ModelAndView("redirect:/report/");
        service.save(workReport);
        attrs.addFlashAttribute(Remind.success().setMessage("保存成功"));
        return mv;
    }

    @Deprecated
    @GetMapping("/add/{date}")
    public ModelAndView addByDate(@PathVariable InputtableDateEnum date) {
        Integer userId = SessionHelper.currentUserId();
        ModelAndView modelAndView = new ModelAndView("report/day-add");
        DayReportVo dayReport = service.getDayReportByDate(userId, date.getDate());
        modelAndView.addObject("day", dayReport);
        modelAndView.addObject("date", date);
        modelAndView.addObject("projects", projectService.mineProject(SessionHelper.currentUserId()));
        return modelAndView;
    }

    @Deprecated
    @GetMapping("/addForm/{day}")
    public ModelAndView addForm(@PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") Date day) {
        ModelAndView mv = new ModelAndView("report/addForm");
        mv.addObject("date", day);
        mv.addObject("projects", projectService.mineProject(SessionHelper.currentUserId()));
        return mv;
    }

    @PostMapping("/addForm/save")
    public BaseResponse addForm(WorkReport workReport) {
        workReport.setUserId(SessionHelper.currentUserId());
        service.save(workReport);
        jiraService.createByCode(workReport.getJira(), workReport.getProjectId(), true);
        return BaseResponse.success(workReport);
    }

    @Override
    protected String home() {
        return "/report/";
    }

    /**
     * 前往新增日报页面：可新增任何一天的日志
     */
    @GetMapping("/insert")
    public ModelAndView insert() {
        ModelAndView mv = new ModelAndView("report/insert");
        mv.addObject("today", InputtableDateEnum.TODAY.getDate());
        mv.addObject("projects", projectService.mineUsableProject(SessionHelper.currentUserId()));
        return mv;
    }

    /**
     * 批量异步json新增
     */
    @PostMapping("/batchInsert")
    public BaseResponse<?> batchInsert(@RequestBody List<WorkReport> list) {
        JsonUtil.printJson(list);
        Integer userId = SessionHelper.currentUserId();

        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(workReport -> {
                workReport.setUserId(userId);
                service.save(workReport);
                jiraService.createByCode(workReport.getJira(), workReport.getProjectId(), true);
            });
        }
        return BaseResponse.success();
    }

    /**
     * 修改某某条记录
     *
     * @param id 日报id
     */
    @GetMapping("/update/{id}")
    public ModelAndView update(@PathVariable Integer id, RedirectAttributes attrs) {
        ModelAndView mv = new ModelAndView("report/update");
        mv.addObject("projects", projectService.mineProject(SessionHelper.currentUserId()));
        WorkReport entity = service.findById(id);
        if (entity == null) {
            return redirectHome("不存在的项目", attrs);
        }
        mv.addObject("entity", entity);
        return mv;
    }

    @PostMapping("/update")
    public ModelAndView update(WorkReport workReport, RedirectAttributes attrs) {
        service.update(workReport);
        return redirectHome(attrs);
    }

    /**
     * 查看项目的总工时
     *
     * @param projectId 项目id
     */
    @GetMapping("/totalTime/{projectId}")
    public BaseResponse<Integer> totalTime(@PathVariable Integer projectId) {
        Integer totalTime = service.totalTime(projectId);
        return BaseResponse.success(totalTime == null ? 0 : totalTime);
    }


    @RequestMapping(value = "export")
    public void exportAll(WorkReportLookup lookup) throws IOException {
        service.export(response, lookup);
    }

}
